﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AvalonDock;
using RiskMan.DataClass;
using System.Collections.ObjectModel;
using RiskMan.DataClass.Models;
using System.Windows.Threading;
using RiskMan.DataClass.Models.RM;
using RiskMan.Views.Dialogs;

namespace RiskMan.Views.RMInvestor
{
    /// <summary>
    /// Логика взаимодействия для RMInvestor.xaml
    /// </summary>
    public partial class RMInvestor : DocumentContent
    {
        private Data _data;
        private ObservableCollection<ModuleInvestorModel> _list;
        private InvestorsLogic _logic = new InvestorsLogic(  );
        private MainWindow mainWindow;
        VerificationLicense vers = new VerificationLicense();

        public static RMInvestor stRMInvestor;
 
        public RMInvestor ( )
        {
            stRMInvestor = this;
            InitializeComponent( );

            mainWindow = RiskMan.MainWindow.StaticRiskMan;
            _data = MainWindow.StaticRiskMan._dataProvider;
            _list = MainWindow.StaticRiskMan._dataProvider.RmInvestorItems;
            CheckConnect( );
            update( );
        }

        #region Основные функции роботов

        #region Выключение роботов

        private void buttonUnrun_Click ( object sender, RoutedEventArgs e )
        {
            vers.RemoveAccountLicense(mainWindow, "RMinvestor");

            for ( int i = 0; i < _list.Count; i++ )
            {
                if ( _list [ i ].Check == true )
                {
                    _list [ i ].Run = false;
                    MainWindow.StaticRiskMan.Terminals.OnTerminalsTransaction += new Providers.QuikIO.QuiksTransEventHandler( _list [ i ].Terminals_OnTerminalsTransaction );
                }
            }
            update( );
        }

        #endregion

        #region Включение роботов

        private void buttonRun_Click ( object sender, RoutedEventArgs e )
        {
            try
            {
                if (vers.CountAccountLicense(mainWindow, "RMinvestor") == false)
                {
                    new DialogOkCancel("Количество запускаемых счетов больше, чем приобретено лицензий. Одна лицензия - один счет ММВБ и один счет ФОРТС", "Предупреждение");
                    return;
                }
            }
            catch
            { 
            
            }

            for ( int i = 0; i < _list.Count; i++ )
            {
                if ( _list [ i ].Check == true )
                {
                    MainWindow.StaticRiskMan.Terminals.OnTerminalsTransaction += new Providers.QuikIO.QuiksTransEventHandler(_list[i].Terminals_OnTerminalsTransaction);
                    _list [ i ].Run = true;
                }
            }
            update( );
        }

        #endregion

        #region Добавить робота

        private void buttonAdd_Click ( object sender, RoutedEventArgs e )
        {
            ModuleInvestorModel item = null;
            ViewAddRMInvestorItem.Show( item, false );
            update( );
        }

        #endregion

        #region Редактировать робота

        private void buttonEdit_Click ( object sender, RoutedEventArgs e )
        {
            if ( dataGridRMInvestor.SelectedItems.Count == 1 )
            {
                ModuleInvestorModel item = ( dataGridRMInvestor.SelectedItem as ModuleInvestorModel );
                var tmp = new ViewAddRMInvestorItem( item, true );
                if ( tmp.Result == System.Windows.Forms.DialogResult.OK )
                    _list [ dataGridRMInvestor.SelectedIndex ] = tmp.ResultItem;
                update( );
            }
            else
            {
            }
        }

        private void dataGridRMInvestor_MouseDoubleClick ( object sender, MouseButtonEventArgs e )
        {
            if ( dataGridRMInvestor.SelectedItems.Count == 1 )
            {
                ModuleInvestorModel item = ( dataGridRMInvestor.SelectedItem as ModuleInvestorModel );
                var tmp = new ViewAddRMInvestorItem( item, true );
                if ( tmp.Result == System.Windows.Forms.DialogResult.OK )
                    _list [ dataGridRMInvestor.SelectedIndex ] = tmp.ResultItem;
                update( );
            }
            else
            {
            }
        }

        #endregion

        #region Удалить робота

        private void buttonDelete_Click ( object sender, RoutedEventArgs e )
        {
            for ( int i = 0; i < _list.Count; i++ )
            {
                if ( _list [ i ].Check == true )
                {
                    _list.RemoveAt( i );
                    i--;
                }
            }
            update( );
        }

        #endregion

        #region выбрать/отменить выбор

        private void dataGridRMInvestor_MouseUp ( object sender, MouseButtonEventArgs e )
        {
            for ( int i = 0; i < dataGridRMInvestor.SelectedItems.Count; i++ )
            {
                if ( false == ( dataGridRMInvestor.SelectedItems [ i ] as ModuleInvestorModel ).Check )
                    ( dataGridRMInvestor.SelectedItems [ i ] as ModuleInvestorModel ).Check = true;
                else ( dataGridRMInvestor.SelectedItems [ i ] as ModuleInvestorModel ).Check = false;
            }

            update( );
        }

        #endregion

        #endregion

        #region обновление UI, DATA

        public void update ( )
        {
            dataGridRMInvestor.ItemsSource = MainWindow.StaticRiskMan._dataProvider.RmInvestorItems;
            dataGridActive.ItemsSource = MainWindow.StaticRiskMan._dataProvider.RmInvestorItems;
        }

        #endregion

        #region проверка соединений

        public bool CheckConnect ( )
        {
            bool running = false;

            if ( MainWindow.StaticRiskMan.Terminals == null )
                running = false;
            else
            {
                if ( MainWindow.StaticRiskMan.Terminals.CountConnected( ) > 0 )
                    running = true;
                else
                    running = false;
            }
            buttonRun.IsEnabled = running;
            buttonUnrun.IsEnabled = running;
            
            return running;
        }

        #endregion        
        private void CheckBox_Click ( object sender, RoutedEventArgs e )
        {
            bool tr = false;
            if ( ( sender as CheckBox ).IsChecked == true )
                tr = true;

            for ( int i = 0; i < _list.Count; i++ )
                _list [ i ].Check = tr;

            update( );
        }
    }
}
